//
//  ZYResponsibilityImp.m
//  DesignMode
//
//  Created by wangzhipan on 2024/11/13.
//

#import "ZYResponsibilityImp.h"

@implementation ZYRequest

@end


@interface BaseChainHandler()
@property (nonatomic, strong, nullable) BaseChainHandler *nextHandler;
@end

@implementation BaseChainHandler
- (void)setNextChain:(BaseChainHandler *)handler
{
    self.nextHandler = handler;
}

- (void)handle:(ZYRequest *)request
{
    if ([self canHandleRequest:request]) {
        [self processRequest:request];
    }
    else {
        [self sendRequestToNextHandler:request];
    }
}

- (void)sendRequestToNextHandler:(ZYRequest *)request
{
    if (self.nextHandler) {
        [self.nextHandler handle:request];
    }
}

- (BOOL)canHandleRequest:(nonnull ZYRequest *)request
{
    return NO;
}
- (void)processRequest:(nonnull ZYRequest *)request
{
    
}
@end


@implementation ZYHandlerOne
- (BOOL)canHandleRequest:(ZYRequest *)request
{
    return request.type == REQ_HANDLER1;
}

- (void)processRequest:(ZYRequest *)request
{
    NSLog(@"ZYHandlerOne:: processRequest");
}
@end


@implementation ZYHandlerTwo
- (BOOL)canHandleRequest:(ZYRequest *)request
{
    return request.type == REQ_HANDLER2;
}

- (void)processRequest:(ZYRequest *)request
{
    NSLog(@"ZYHandlerTwo:: processRequest");
}
@end


@implementation ZYHandlerThree
- (BOOL)canHandleRequest:(ZYRequest *)request
{
    return request.type == REQ_HANDLER3;
}

- (void)processRequest:(ZYRequest *)request
{
    NSLog(@"ZYHandlerThree:: processRequest");
}
@end


@implementation ZYHandlerMainPage
- (void)setup
{
    BaseChainHandler *handler1 = [[ZYHandlerOne alloc] init];
    BaseChainHandler *handler2 = [[ZYHandlerTwo alloc] init];
    BaseChainHandler *handler3 = [[ZYHandlerThree alloc] init];
    
    [handler1 setNextChain:handler2];
    [handler2 setNextChain:handler3];
    
    ZYRequest *request = [[ZYRequest alloc] init];
    request.type = REQ_HANDLER3;
    
    [handler1 handle:request];
}
@end
